#include "../comm/httplib.h"
#include <string>
#include <mysql/mysql.h>
#include <jsoncpp/json/json.h>
#include <ctemplate/template.h>
#include "head_mysql.hpp" // 包含数据库连接函数
#include "cookie.hpp"     // 包含 check_cookie 和 is_valid_session 函数

using namespace std;

// 处理 /user_center 请求的方法
void handle_user_center(const httplib::Request &req, httplib::Response &res)
{
    // 提取 session_id
    auto cookies = req.get_header_value("Cookie");
    std::string session_id;
    size_t pos = cookies.find("sessionid=");
    if (pos != std::string::npos)
    {
        size_t start = pos + strlen("sessionid=");
        size_t end = cookies.find(';', start);
        if (end == std::string::npos)
        {
            end = cookies.length();
        }
        session_id = cookies.substr(start, end - start);
    }

    // 连接到数据库
    MYSQL *conn = connect_db();
    if (conn == nullptr)
    {
        res.set_content("Database connection failed", "text/plain");
        res.status = 500; // Internal Server Error
        return;
    }

    // 构建 SQL 查询，从 session_id 中获取用户信息
    std::string query = "SELECT BID, username, email FROM users WHERE session_id = '" + session_id + "'";
    if (mysql_query(conn, query.c_str()))
    {
        res.set_content("Query execution failed", "text/plain");
        mysql_close(conn);
        res.status = 500;
        return;
    }

    MYSQL_RES *result = mysql_store_result(conn);
    if (result == nullptr)
    {
        res.set_content("Result retrieval failed", "text/plain");
        mysql_close(conn);
        res.status = 500;
        return;
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    if (!row)
    {
        res.set_content("User not found", "text/plain");
        mysql_free_result(result);
        mysql_close(conn);
        res.status = 404; // Not Found
        return;
    }

    std::string bid = row[0];
    std::string username = row[1];
    std::string email = row[2];

    // 清理
    mysql_free_result(result);
    mysql_close(conn);

    // 使用 ctemplate 渲染 HTML 页面
    ctemplate::TemplateDictionary dict("user_center");
    dict.SetValue("BID", bid);
    dict.SetValue("USERNAME", username);
    dict.SetValue("EMAIL", email);

    std::string output;

    ctemplate::Template *tpl = ctemplate::Template::GetTemplate("./wwwroot/user_center.html", ctemplate::DO_NOT_STRIP);
    tpl->Expand(&output, &dict);

    res.set_content(output, "text/html");
    res.status = 200; // OK
}
